// zagSNES
// © MIT ∞ IamRifki

const std = @import("std");
const cpu = @import("./65c816.zig");

const c = @cImport({
    @cInclude("SDL2/SDL.h");
});

/// Video
var nmi: i16 = undefined;
var vbl: i16 = undefined;
var joyScan: i16 = undefined;
var nmiEnable: i16 = undefined;
var vRamB: u8 = undefined;
var vRam: u16 = undefined;
var ppuMask: i16 = undefined;

var yIrq: i16 = undefined;
var xIrq: i16 = undefined;
var irqEnable: i16 = undefined;
var irq: i16 = undefined;
var lines: i16 = undefined;

var skipZ: i16 = undefined;
var setZF: i16 = undefined;

var pal: i16 = undefined;

/// DMA Registers
var dmadest: [8]u16 = undefined;
var dmasrc: [8]u16 = undefined;
var dmalen: [8]u16 = undefined;
var hdmaaddr: [8]u32 = undefined;
var hdmaaddr2: [8]u32 = undefined;
var dmabank: [8]u8 = undefined;
var dmaibank: [8]u8 = undefined;
var dmactrl: [8]u8 = undefined;
var hdmastat: [8]u8 = undefined;
var hdmadat: [8]u8 = undefined;
var hdmacount: [8]i16 = undefined;
var hdmaena: u8 = undefined;

var voiceOn: u8 = undefined;

fn cgAdd(x: u32, y: u32) u16 {
    var sum: usize = x + y;
    var carries: usize = (sum - ((x ^ y) & 0x0821)) & 0x10820;
    return (sum - carries) | (carries - (carries >> 5));
}

fn cgAddH(x: u32, y: u32) u16 {
    return (x + y - ((x ^ y) & 0x0821)) >> 1;
}

fn cgSub(x: u32, y: u32) usize {
    var sub: u8 = x - y;
    var borrows: u8 = (~(sub + ((~(x ^ y)) & 0x10820))) & 0x10820;
    sub += borrows;
    return sub & ~(borrows - (borrows >> 5));
}

fn cgSubH(x: u32, y: u32) u16 {
    var sub: u8 = x - y;
    var borrows: u8 = (~(sub + ((~(x ^ y)) & 0x10820))) & 0x10820;
    sub += borrows;
    return sub & ~(borrows - (borrows >> 5));
}

var wroteAddr: u32 = undefined;
var hCount: isize = undefined;
var vCount: isize = undefined;
var window: [10][164]u32 = undefined;
var twoWrite: isize = 0;
var windowsChanged: isize = undefined;

const rgbColor: packed struct {
    var r: u8 = undefined;
    var g: u8 = undefined;
    var b: u8 = undefined;
};

const ppu: struct {};
